package com.atguigu.gulimall.ware.mq;

import com.atguigu.common.To.mq.OrderTo;
import com.atguigu.common.To.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 普通对列stock-release-stock
 * 死性队列路由给普通对列
 */
@Service
@RabbitListener(queues = "stock-release-stock")
public class StockListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 回滚库存 锁库存后发送延迟消息
     * @param to
     * @param msg
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelase(StockLockedTo to, Message msg, Channel channel) throws IOException {

        try {
            wareSkuService.unLockStock(to);
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(),false);
        }
    }

    @RabbitHandler
    public void OrderWareClose(OrderTo orderTo, Message msg, Channel channel ) throws IOException {
        //订单状态已取消 回滚库存 订单解锁
        try {
            wareSkuService.OrderWareClose(orderTo);
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
